package databases
import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"hulk-api/conf"
	"os"
	"log"
	"fmt"
)

var SqlDB *sql.DB

func checkErr(err error)  {
	if err != nil {
		log.Println(err)
	}
}

func checkFatal(err error)  {
	if err != nil {
		log.Println(err)
		os.Exit(3)
	}
}

func init() {
	var err error
	dbuser ,err := conf.Cfg.GetValue("mysql","username")
	checkErr(err)
	dbpassword ,err := conf.Cfg.GetValue("mysql","password")
	checkErr(err)
	dbhost ,err := conf.Cfg.GetValue("mysql","hostname")
	checkErr(err)
	dbName ,err := conf.Cfg.GetValue("mysql","database")
	checkErr(err)
	//dataSourceUrl := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":3306)/" + dbName + "?charset=utf8mb4&parseTime=true&loc=Local"
	dataSourceUrl := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8mb4&parseTime=true&loc=Local",dbuser,dbpassword,dbhost,dbName)
	log.Println("begin connect to mysql",dataSourceUrl)
	SqlDB, err = sql.Open("mysql", dataSourceUrl)
	checkErr(err)
	err = SqlDB.Ping()
	checkFatal(err)
}